package edu.dlust.trading_platform;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.yalantis.ucrop.UCrop;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Date;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBean.userdata;

public class ModifyGoodsActivity extends AppCompatActivity {
    private ImageView back, goods;
    private EditText content, price, type;
    private Spinner spinner1, spinner2;
    private Button del, add, confirm;
    private TextView inv;
    private CheckBox self,exp;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static Uri tempUri;
    private Bitmap mBitmap;
    private String fineness = "<-- 未选择 -->";
    private String classification = "<-- 未选择 -->";
    private String selfPickup = "";
    private String express = "";
    private String goodsId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_goods);

        goodsId = getIntent().getStringExtra("goodsId");

        spinner1 = findViewById(R.id.spinner1);
        spinner2 = findViewById(R.id.spinner2);

        // 准备数据源
        String[] fineness = new String[]{"<-- 未选择 -->", "全新", "九成新", "八成新", "七成新", "六成新", "破损"};
        String[] item = new String[]{"<-- 未选择 -->", "书本", "电子产品", "服装", "日用品", "其他"};

        // 创建 ArrayAdapter 并设置数据源
        ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, fineness);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter1);

        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, item);
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner2.setAdapter(adapter2);



        initUI();
        DelImg();
        submit();
        inset();

        back = findViewById(R.id.publish_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ModifyGoodsActivity.this.finish();
            }
        });
    }

    private void initUI() {
        goods = findViewById(R.id.publish_img);
        del = findViewById(R.id.button_del_image);
        add = findViewById(R.id.button_add_image);
        AddImg();
    }

    private void AddImg() {
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 检查并请求权限
                if (ContextCompat.checkSelfPermission(ModifyGoodsActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(ModifyGoodsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(ModifyGoodsActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ModifyGoodsActivity.this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            100); // 请求码
                } else {
                    showChoosePicDialog();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showChoosePicDialog();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ModifyGoodsActivity.this);
        builder.setTitle("添加图片");
        String[] items = {"选择本地照片", "拍照"};
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                        break;
                    case TAKE_PICTURE: // 拍照
                        File photoFile = null;
                        try {
                            photoFile = createImageFile();
                        } catch (IOException ex) {
                            Log.e("PublishActivity", "Error creating image file: " + ex.getMessage());
                        }
                        if (photoFile != null) {
                            tempUri = FileProvider.getUriForFile(ModifyGoodsActivity.this,
                                    BuildConfig.APPLICATION_ID + ".provider",
                                    photoFile);
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                            startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        }
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_PICTURE:
                    cutImage(data.getData()); // 对图片进行裁剪处理
                    break;
                case TAKE_PICTURE:
                    // 授予临时权限
                    if (tempUri != null) {
                        grantUriPermission(getPackageName(), tempUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    }
                    cutImage(tempUri); // 对图片进行裁剪处理
                    break;
                case UCrop.REQUEST_CROP:
                    final Uri resultUri = UCrop.getOutput(data);
                    setImageToView(resultUri);
                    break;
                case UCrop.RESULT_ERROR:
                    final Throwable cropError = UCrop.getError(data);
                    Log.e("UCrop", "Crop error: " + cropError);
                    break;
            }
        }
    }

    protected void cutImage(Uri uri) {
        if (uri == null) {
            Log.i("alanjet", "The uri is not exist.");
            return;
        }
        tempUri = uri;
        UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), "cropped_image.jpg")))
                .withAspectRatio(1, 1)
                .withMaxResultSize(150, 150)
                .start(ModifyGoodsActivity.this);
    }

    protected void setImageToView(Uri uri) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            goods.setImageBitmap(bitmap);
            mBitmap = bitmap;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void DelImg() {
        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 清除ImageView中的图片
                goods.setImageBitmap(null);
                mBitmap = null;

                // 如果有临时文件，删除它
                if (tempUri != null) {
                    File file = new File(tempUri.getPath());
                    if (file.exists()) {
                        file.delete();
                    }
                    tempUri = null;
                }
                Drawable yourDrawable = getResources().getDrawable(R.drawable.noimage);
                mBitmap = drawableToBitmap(yourDrawable);
            }
        });
    }

    public Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        // 如果不是BitmapDrawable，则创建一个空白的Bitmap，并将Drawable绘制到这个Bitmap上
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        return image;
    }

    private void submit(){
        content = findViewById(R.id.editText_content);
        price = findViewById(R.id.editText_price);
        type = findViewById(R.id.TypeEditText);

        self = findViewById(R.id.checkBox_selfPickup);
        exp = findViewById(R.id.checkBox_express);

        inv = findViewById(R.id.TextView_inv);

        confirm = findViewById(R.id.button_confirm_publish);

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                fineness = (String) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                classification = (String) parent.getItemAtPosition(position);

                if (classification.equals("其他")){
                    type.setVisibility(View.VISIBLE);
                    inv.setVisibility(View.VISIBLE);
                }else {
                    type.setVisibility(View.INVISIBLE);
                    inv.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        self.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    selfPickup = " 自取";
                }else {
                    selfPickup = "";
                }
            }
        });

        exp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    express = " 快递";
                }else {
                    express = "";
                }
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBitmap == null) {
                    try {
                        Drawable drawable = goods.getDrawable();
                        mBitmap = ((BitmapDrawable) drawable).getBitmap();
                    } catch (Exception e) {
                    }
                }
                String substance = content.getText().toString();
                String prices = price.getText().toString();
                String types = type.getText().toString();

                if (classification.equals("其他")){
                    if(substance.equals("") || prices.equals("") || types.equals("") || fineness.equals("<-- 未选择 -->")){
                        Toast.makeText(ModifyGoodsActivity.this, "请正确选择以及填写以上信息", Toast.LENGTH_SHORT).show();
                    }else {
                        if (selfPickup.equals("") && express.equals("")){
                            Toast.makeText(ModifyGoodsActivity.this, "请选择至少一个发货方式", Toast.LENGTH_SHORT).show();
                        }else {
                            if (mBitmap == null) {
                                prompt(substance,fineness,types,prices,selfPickup+express,null,goodsId);
                            } else {
                                UpdateMySQL(substance,fineness,types,prices,selfPickup+express,HandleImg(mBitmap),goodsId);
                            }
                        }
                    }
                }else {
                    if(substance.equals("") || prices.equals("") || fineness.equals("<-- 未选择 -->") || classification.equals("<-- 未选择 -->")){
                        Toast.makeText(ModifyGoodsActivity.this, "请正确选择以及填写以上信息", Toast.LENGTH_SHORT).show();
                    }else {
                        if (selfPickup.equals("") && express.equals("")){
                            Toast.makeText(ModifyGoodsActivity.this, "请选择至少一个发货方式", Toast.LENGTH_SHORT).show();
                        }else {
                            if (mBitmap == null) {
                                prompt(substance,fineness,classification,prices,selfPickup+express,null,goodsId);
                            } else {
                                UpdateMySQL(substance,fineness,classification,prices,selfPickup+express,HandleImg(mBitmap),goodsId);
                            }
                        }
                    }
                }
            }
        });
    }

    public void prompt(String Content, String Fineness, String Classification, String Price, String Type, byte[] Image, String id){
        AlertDialog.Builder builder = new AlertDialog.Builder(ModifyGoodsActivity.this);
        builder.setTitle("提示");
        builder.setMessage("您还没有上传图片，确认要发布吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UpdateMySQL(Content,Fineness,Classification,Price,Type,Image,id);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    public byte[] HandleImg(Bitmap bitmap){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); // 也可以使用JPEG等其他格式
        return stream.toByteArray();
    }

    public void UpdateMySQL(String Content, String Fineness, String Classification, String Price, String Type, byte[] Image, String id) {
        String sql = "UPDATE GOODS SET Content = ?, Fineness = ?, Classification = ?, Price = ?, Type = ?, Image = ? WHERE id = ?";

        new Thread(new Runnable() {
            @Override
            public void run() {
                Connection con = MySQL.getConnection();
                try {
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setString(1, Content);
                    ps.setString(2, Fineness);
                    ps.setString(3, Classification);
                    ps.setString(4, Price);
                    ps.setString(5, Type);
                    if (Image != null) {
                        ps.setBytes(6, Image);
                    } else {
                        ps.setNull(6, Types.BLOB);
                    }
                    ps.setString(7, id);

                    int rowsAffected = ps.executeUpdate();

                    if (rowsAffected >= 1) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ModifyGoodsActivity.this, "更新成功！", Toast.LENGTH_SHORT).show();

                            }
                        });
                        ModifyGoodsActivity.this.finish();
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ModifyGoodsActivity.this, "更新失败！", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    con.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void inset(){
        String str = "SELECT Content, Fineness, Classification, Price, Type, Image, Buyer FROM GOODS WHERE id = ?;";
        new Thread(new Runnable() {
            @Override
            public void run() {
                Connection con = MySQL.getConnection();
                try {
                    PreparedStatement selectStatement = con.prepareStatement(str);
                    selectStatement.setString(1, goodsId); // 替换为您要查询的id值

                    ResultSet resultSet = selectStatement.executeQuery();

                    while (resultSet.next()) {
                        // 从结果集中获取数据
                        String Dcontent = resultSet.getString("Content");
                        String Dfineness = resultSet.getString("Fineness");
                        String Dclassification = resultSet.getString("Classification");
                        String Dprice = resultSet.getString("Price");
                        String Dtype = resultSet.getString("Type");
                        byte[] Dimage = resultSet.getBytes("Image");
                        String buyer = resultSet.getString("Buyer");

                        if (buyer == null){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    content.setText(Dcontent);
                                    if (Dimage != null) {
                                     Bitmap bitmap = BitmapFactory.decodeByteArray(Dimage, 0, Dimage.length);
                                        try{
                                            goods.setImageBitmap(bitmap);
                                        } catch (Exception e) {
                                     }
                                  }
                                  String[] fineness = new String[]{"<-- 未选择 -->", "全新", "九成新", "八成新", "七成新", "六成新", "破损"};
                                   String[] item = new String[]{"<-- 未选择 -->", "书本", "电子产品", "服装", "日用品", "其他"};
                                   int position1 = -1;
                                    for (int i = 0; i < fineness.length; i++) {
                                      if (fineness[i].equals(Dfineness)) {
                                            position1 = i;
                                            break;
                                        }
                                    }
                                    if (position1 != -1) {
                                        spinner1.setSelection(position1);
                                    } else {
                                        spinner1.setSelection(0);
                                    }
                                   int position2 = -1;
                                    for (int i = 0; i < item.length; i++) {
                                        if (item[i].equals(Dclassification)) {
                                           position2 = i;
                                            break;
                                        }
                                    }
                                   if (position2 != -1) {
                                spinner2.setSelection(position2);
                                 } else {
                                        spinner2.setSelection(5);
                                        type.setText(Dclassification);
                                 }
                                 price.setText(Dprice);
                                 if (Dtype.contains("自取")) {
                                     self.setChecked(true);
                                   }

                                    if (Dtype.contains("快递")) {
                                       exp.setChecked(true);
                                     }
                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ModifyGoodsActivity.this, "已经被购买的商品不能被修改！", Toast.LENGTH_SHORT).show();
                                    ModifyGoodsActivity.this.finish();
                                }
                            });
                        }
                    }
                    con.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}